package com.cn.wanxi.service;

import com.cn.wanxi.IOModel.NewsIOModel;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.util.Path;
import com.cn.wanxi.util.ReadAndWriteIO;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NewsService {
    /**
     * 得到网站首页的较新动态新闻数据
     *
     * @return
     */
    public List<NewsModel> getNewsListForHome() {
//        写
        writeNote();
//        读
        String result = new ReadAndWriteIO().readNote(Path.NEWS_PATH.getPath());
//        封装
        return setData(result);
    }

    private List<NewsModel> setData(String result) {
        String[] results = result.split(Path.SPLIT.getPath());
        String title = results[0];
        String content = results[1];
        title = title.replace("[", "").replace("]", "");
        content = content.replace("[", "").replace("]", "");
        List<NewsModel> list = new ArrayList<>();
        String[] titles = title.split(",");
        String contents[] = content.split(",");
        for (int i = 0; i < titles.length; i++) {
            NewsModel newsModel = new NewsModel();
            newsModel.setTitle(titles[i]);
            newsModel.setContent(contents[i]);
            list.add(newsModel);
        }
        return list;
    }

    private void writeNote() {
        NewsIOModel newsIOModel = new NewsIOModel();
        String titles[] = newsIOModel.getTitles();
        String[] contents = newsIOModel.getContents();
        List<String> list = new ArrayList<>();
        list.add(Arrays.toString(titles));
        list.add(Arrays.toString(contents));
        new ReadAndWriteIO().createNote(Path.NEWS_PATH.getPath(), list);
    }
}
